<script setup>
import { ref, computed } from 'vue';
import { useRoute, useRouter, onBeforeRouteUpdate } from 'vue-router';
import { Sidebar, SidebarItem, Card, List } from 'vant'
import { useCategories } from '../hooks/use-categories'
import { useProducts } from '../hooks/use-products';
import { dalImg } from '../utils/tools'

const route = useRoute()
const router = useRouter()
const { categories } = useCategories()
const { loading, finished, currentCategoryId, products, loadDataFromServer } = useProducts(route.query.tid)

const active = computed({
    set(v) {
        return v
    },
    get() {
        return categories.value.findIndex(item => item.id == currentCategoryId.value)
    }
})

const toDetail = (id) => {
    router.push({ name: 'Detail', query: { id } })
}

// onBeforeRouteUpdate 路由改变，但是组件复用的时候执行(切换左侧的产品分类)
onBeforeRouteUpdate((to, from) => {
    // 需要重置数据
    loadDataFromServer(true, to.query.tid)
})
</script>

<template>
    <div class="list">
        <!-- <h1>列表</h1>
        <router-link v-for="item in categories" :key="item.id" :to="{ name: 'List', query: { tid: item.id } }">【{{ item.name
        }}】</router-link> -->
        <sidebar v-model="active">
            <sidebar-item v-for="item in categories" :key="item.id" :title="item.name"
                :to="{ name: 'List', query: { tid: item.id } }" />
        </sidebar>

        <list class="product" :loading="loading" :finished="finished" finished-text="没有更多了" @load="loadDataFromServer">
            <card v-for="item in products" :num="item.amount" :price="item.price.toFixed(2)" :title="item.name"
                :thumb="dalImg(item.coverImage)" @click-thumb="toDetail(item.id)" />
        </list>
    </div>
</template>

<style scoped>
.list {
    display: flex;
}

.list .van-sidebar {
    width: 98px;
}

.product {
    overflow: auto;
    flex: 1;
}
</style>